package com.runfast.waimai.web.controller.Driver_controller;

import com.alibaba.fastjson.JSON;
import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.OrderStatusHistory;
import com.runfast.paotui.dao.model.RunfastCuser;
import com.runfast.paotui.dao.model.RunfastShopper;
import com.runfast.paotui.service.*;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.util.*;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/shopper/*")
public class ShopperIndexController extends DriverBaseController {
    @Resource
    OrderService orderService;
    @Resource
    private RunfastGoodsSellRecordService goodsSellRecordService;
    //RunfastGoodsSellRecord// 外卖商品订单
    @Resource
    private RunfastBusinessService businessService;
    //RunfastBusiness商家信息

    @Resource
    private RunFastSettingts runFastSettingts;
    //处理接单
    @Resource
    private RunfastShopperService shopperService;
    //骑手信息
    @Resource
    private RunfastGoodsSellOutStatusService goodsSellOutStatusService;
    // 外卖商品配送状态
    @Resource
    private RunfastTransorderService transOrderService;
    //转单信息

    @Resource
    private RunfastGoodsSellChildrenService goodsSellRecordChildrenService;
    /// 外卖商品订单记录子类

    @Resource
    private RunfastCreditlevelService creditLevelService;
    //信用等级管理
    @Resource
    private RunfastCuserService cuserService;
    @Resource
    private RunfastAgentbusinessService runfastAgentbusinessService;
    @Resource
    private OrderStatusHistoryService orderStatusHistoryService;
    @Resource
    private AmqpTemplate amqpTemplate; //队列推送
    ////用户信息
    /**
     * ȡ跑腿取货
     */
  //  @RequestMapping(value="ordertake",method=RequestMethod.POST)//验证֤
    @PostMapping("ordertake")
    public @ResponseBody ModelMap ordertake(Integer id,String token){
        ModelMap model = new ModelMap();
        RunfastShopper shopper=super.getLoginShopper(token);

        if(shopper!=null && id!=null) {

            Order gr = orderService.findByShopperidAndCode(shopper.getId(), id);
            System.out.println( gr+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

            if(gr!=null){
                if (!gr.getDriverId().equals(shopper.getId())) {
                    System.out.println("该订单为其他骑手订单");
                    model.put("success", false);
                    model.put("msg", "该订单为其他骑手订单");

                }else {
                    if (gr.getStatus() == Order.Status.TAKEN){
                        OrderStatusHistory orderStatusHistory=new OrderStatusHistory();
                        orderStatusHistory.setId(null);
                        orderStatusHistory.setStatus(Order.Status.PICKED);//状态为5
                        orderStatusHistory.setOrderId(gr.getId());
                        orderStatusHistory.setCreateTime(new Date());
                        orderStatusHistory.setUpdateTime(new Date());
                        orderStatusHistoryService.insertSelective(orderStatusHistory);//待送达

                   //     gr.setTimep(new Date());//设置处货时间
                        gr.setStatus(Order.Status.PICKED);//设置为待送达状态
                //        gr.setTaken(true);
                        gr.setDriverId(super.getLoginShopper(token).getId());
                        orderService.updateByPrimaryKeySelective(gr);
                   //     this.rabbitTemplate.convertAndSend("paotui", JSON.toJSONString(gr)); //保存在队列
                        amqpTemplate.convertAndSend("pt_shopper_order_exchange", "", JSON.toJSONString(gr));
                        RunfastCreditlevel runfastCreditlevel=  creditLevelService.get(shopper.getCreditLevelid());
                        RunfastCreditlevel c=null;// // 信用等级管理
                        if(shopper.getCreditLevelid()!=null){
                            c=creditLevelService.get(shopper.getCreditLevelid());//查看信誉等级情况
                        }else{
                            List<RunfastCreditlevel> list=  creditLevelService.findAll();//  信用等级管理
                            if(list!=null&&list.size()>0){
                                c=list.get(0);
                            }
                        }

//                        if(c!=null){
//                            BigDecimal shopperMoney=BigDecimal.valueOf(0);
//                            if(c.getStarttimeday()!=null && c.getEndtimeday()!=null){
//                                //白班开始时间              //白班结束时间
//                                Calendar calendar = Calendar.getInstance();
//                                int hour = calendar.get(Calendar.HOUR_OF_DAY);
//                                calendar.setTime(c.getStarttimeday());
//                                int startTime1 = calendar.get(Calendar.HOUR_OF_DAY);
//                                calendar.setTime(c.getEndtimeday());
//                                int endTime1 = calendar.get(Calendar.HOUR_OF_DAY);
//                                if(MyUtil.inTime(c.getStarttimeday(), c.getEndtimeday(), new Date())){
//                                    //符合第一时段配送费
//                                    shopperMoney=c.getCommissionday();  //白班每笔订单提成
//
//                                }else{
//                                    shopperMoney=c.getCommissionnight();  ////晚班每笔订单提成
//                                }
//                                if(shopperMoney==null){
//                                    shopperMoney=BigDecimal.valueOf(0);
//                                }
//                                if(gr.getDistance()!=null){
//                                    //// 配送距离
//                                    if(gr.getDistance()!=null&&c.getDistan()!=null&&c.getPrice()!=null){//distan超出多少公里后额外加钱
//                                        Double distan=c.getDistan(); //超出多少公里后额外加钱
//                                        if(Double.parseDouble(String.valueOf(gr.getDistance()))>distan*1000){
//                                            //当超出了范围后，计算超出的费用
//                                            double ss =  Double.parseDouble(String.valueOf(gr.getDistance())) - distan*1000;
//                                            ss = ss /1000;
//                                            if(ss%1!=0){
//                                                ss=  ss+1;
//                                            }
//                                            int sd = (int)ss;
//                                            BigDecimal priceshopper = c.getPrice().multiply(BigDecimal.valueOf(sd));  //额外每公里加多少钱
//                                            shopperMoney=shopperMoney.add(priceshopper);
//                                            if(c.getMaxprice()!=null){
//                                                if(shopperMoney.compareTo(c.getMaxprice())==1){
//                                                    shopperMoney = c.getMaxprice();
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                                gr.setDriverIncome(shopperMoney.intValue());
//                                System.out.println(runfastCreditlevel.getCommission().intValue()+"wQQQQQQQQQQQQQQQQQQQQQQ");
//                                orderService.updateByPrimaryKeySelective(gr);
//
//                            }
//                        }


//                        shopper.getCoefficient();
//                        gr.getAmountPayable();//商家部分金额
//
//                         gr.getDeliveryCost();//配送费
    //                    String.valueOf(gr.getAmountPayable()-gr.getDeliveryCost());
    //                    System.out.println(gr.getDeliveryCost()+"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");

//                        System.out.println(shopper.getCoefficient()+"QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ");
//                        System.out.println( gr.getAmountPayable()+"QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ");//应支付金额
      //                  (1-Coefficient)
          //              gr.getAmountPayable()
//                        com.runfast.paotui.dao.model.RunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.findByid(gr.getAgentId());
//                        gr.setDriverIncome(gr.getAmountPayable()*(1-runfastAgentbusiness.getPaotuiCoefficient().intValue()/100-shopper.getCoefficient().intValue()/100));//骑手收入
//                        gr.setPlateformIncome(gr.getAmountPayable()*runfastAgentbusiness.getPaotuiCoefficient().intValue()/100);//平台所得
//                        gr.setAgentIncome(gr.getAmountPayable()*shopper.getCoefficient().intValue()/100);//代理所得

                        orderService.updateByPrimaryKeySelective(gr);//更新状态
                        System.out.println(gr+"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
                        model.put("success",true);
                        model.put("msg","取货成功");
                    }else {
                  //      gr.setStatus(Order.Status.TAKEN);
                        model.put("msg", "货物已代购中!");
                        model.put("success", false);
                    }
                }
            }else {
                model.put("success",false);
                 model.put("msg","定单信息有误");}

//            //通过骑手ID ,定单号获得外卖商品规格 super.getLoginShopper().getId()
//            // 外卖商品订单
//            if (!gr.getDriverId().equals(super.getLoginShopper(token).getId())) {
//                System.out.println("该订单为其他骑手订单");
//                model.put("success", false);
//                model.put("msg", "该订单为其他骑手订单");
//
//            } else {
//                if (gr != null) {
//                    //  0  created=下单成功 1canceled=取消订单  2paid=接单成功 3taken=排列 4completed==订单完成
//                    if (gr.getStatus() == Order.Status.CREATED) {
//                        ////订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
//                        gr.setStatus(Order.Status.PAID);//设置为配送状态
//
//                        orderService.updateByPrimaryKeySelective(gr);//更新状态
//                        if (gr.getCanceled() != null && gr.getCanceled() == true) {
//                            ///用户申请取消订单
//                            System.out.println("用户申请取消该订单，请等待商家审核!");
//                            String msg = "用户申请取消该订单，请等待商家审核!";
//                            model.put("msg", msg);
//
//                        } else {
// //                           if (gr.getStatus() == Order.Status.CREATED) {
//                                //           RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();//  外卖商品配送状态
//
//                                //      goodsSellOutStatus.setBusinessid(gr.getBusinessid());//商家ID
//                                //      goodsSellOutStatus.setBusinessname(gr.getBusinessname());//商家 名称
////                            goodsSellOutStatus.setCreatetime(new Date());//状态时间
////                            goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());//设置定单号
////                            goodsSellOutStatus.setGoodssellrecordid(gr.getId());//设置外卖商品id
////                            goodsSellOutStatus.setSort(4);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
////                            goodsSellOutStatus.setType(2);//  操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
////                            goodsSellOutStatus.setStatstr("商品打包");
////                            RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
////                            if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(4))){
////                                ////   sort 订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
////                                goodsSellOutStatusService.save(goodsSellOutStatus);
////                            }
// //                           }
//
//                            //订单状态操作记录
////                        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();//  外卖商品配送状态
////
////                        goodsSellOutStatus.setCreatetime(new Date());
////                        goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());
////                        goodsSellOutStatus.setGoodssellrecordid(gr.getId());
////                        goodsSellOutStatus.setOperationid(super.getLoginShopper().getId());
////                        goodsSellOutStatus.setOperationname(super.getLoginShopper().getName());
////                        goodsSellOutStatus.setSort(5);
////                        goodsSellOutStatus.setStatstr("商品配送");
////                        goodsSellOutStatus.setType(2);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
////                        RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);////  外卖商品配送状态
////                        if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(5))){
////                            goodsSellOutStatusService.save(goodsSellOutStatus);
////                        }
//                            System.out.println("\"货物已代购配送中!\"");
//                            model.put("msg", "货物已代购配送中!");
//                            model.put("success", true);
//                        }
//
//                    }
//                } else {
//
//                    model.put("success", false);
//                    model.put("msg", "请先签到再取！");
//
//                }
//            }
//            }else{
//                model.put("success", false);
//                model.put("msg", "数据不正确");
//
          }else {
            model.put("success",false);
            model.put("msg","没有登陆");
        }
//

        return model;
    }

    /**
     * 抢单
     */
    @RequestMapping(value="orderfight",method=RequestMethod.POST)///验证
    public @ResponseBody ModelMap orderfight(@RequestParam(value="id",required=false) Integer id,String token,@RequestParam(value = "page",required = false,defaultValue = "0") Integer page,
                                             @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize){ //定单ID
        Integer page1=page*pageSize;
        ModelMap model = new ModelMap();
     //   String msg ="参数错误";
        boolean isSuccess = false;
        if(super.getLoginShopper(token)!=null&&id!=null){
            RunfastShopper runfastShopper=super.getLoginShopper(token);
            int size=0;
            Integer num=runfastShopper.getDistributionmun();//  配送最大数量

            RunfastCreditlevel runfastCreditlevel = creditLevelService.selectByPrimaryKey(runfastShopper.getCreditLevelid());
            //查看骑手信誉等级问题
            if(runfastShopper.getCreditLevelid()==null || runfastCreditlevel==null){
                model.put("level",false);//false当前骑手绑定等级信誉不存在，或者绑定错误
                model.put("success", false);
                model.put("errormsg", "当前信誉值不存在，请尽快联系代理商");
                return model;
            }

            if(num==null){
                num=5;
            }

            List<RunfastGoodsSellRecord> list1= goodsSellRecordService.findByShopperIdAndStrutsSize(super.getLoginShopper(token).getId());

            List<Order> glist = orderService.findByShopperidAndStatusSize(super.getLoginShopper(token).getId());
            //System.out.println(size+"跑腿的定单数量" );
            //System.out.println(list1.size()+"跑腿的定单数量" );

            // 外卖商品订单
            if(glist!=null){
                size=glist.size(); //获得骑手手上的订单的数量
            }
            if((size+list1.size())<num+1){
                //小于5+1，说明还可以接单
                if(!runFastSettingts.hasTakeThatOrderId(id)){
                    // * 判断是否有人正在执行该订单的接单操作定单
                    runFastSettingts.addTakeThatOrderId(id);//添加正在接单操作的订单id

                    Order gr = orderService.get(id);//订单ID 获得订单信息
                    if(gr!=null&&gr.getDriverId()==null&&gr.getStatus()!=null&&(gr.getStatus()==Order.Status.PAID)){
                        //1：客户已付款
                        gr.setDriverId(super.getLoginShopper(token).getId());//设置骑手id
                        gr.setTimePaid(new Date());//设置支付时间
                        /*if(gr.getBookTime()==null){
                            System.out.println(1111+"*********************************");
                            //gr.setBookTime(gr.getCreateTime());
                        }else {
                            System.out.println("2222222222222221111*********************************");
                        }*/

                //        gr.setDriver(super.getLoginShopper(token).getName());//设置骑手名字
                       // gr.setShoppermobile(super.getLoginShopper().getMunber());//设置骑手 的手机号

                        com.runfast.paotui.dao.model.RunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.findByid(gr.getAgentId());
                        //System.out.println(runfastAgentbusiness+"#################################");
                        //System.out.println(runfastAgentbusiness.getPaotuiCoefficient().intValue()+"########################################");
                        //System.out.println(runfastShopper.getCoefficient().intValue()/100+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                        /*gr.setDriverIncome(gr.getAmountPayable()*(1-runfastAgentbusiness.getPaotuiCoefficient().intValue()/100-runfastShopper.getCoefficient().intValue()/100));//骑手收入
                        gr.setPlateformIncome(gr.getAmountPayable()*runfastAgentbusiness.getPaotuiCoefficient().intValue()/100);//平台所得
                        gr.setAgentIncome(gr.getAmountPayable()*runfastShopper.getCoefficient().intValue()/100);//代理所得*/
                        //gr.setDriverIncome((int) (gr.getAmountPayable()*(1-runfastAgentbusiness.getPaotuiCoefficient().doubleValue()/100-runfastShopper.getCoefficient().doubleValue()/100)));//骑手收入
                        //gr.setPlateformIncome((int) (gr.getAmountPayable()*runfastAgentbusiness.getPaotuiCoefficient().doubleValue()/100));//代理所得
                        //gr.setAgentIncome((int) (gr.getAmountPayable()*runfastShopper.getCoefficient().doubleValue()/100));//平台所得

                        gr.setDriverIncome((int) (gr.getDeliveryCost()*(1-runfastAgentbusiness.getPaotuiCoefficient().doubleValue()/100-runfastShopper.getCoefficient().doubleValue()/100)));//骑手收入
                        gr.setAgentIncome((int) (gr.getDeliveryCost()*runfastAgentbusiness.getPaotuiCoefficient().doubleValue()/100));//代理商抽成
                        gr.setPlateformIncome((int) (gr.getDeliveryCost()*runfastShopper.getCoefficient().doubleValue()/100));//平台抽成

                        //用戶打賞+配送費
                        if(gr.getTip()!=null){
                            gr.setDriverIncome((int) (gr.getDeliveryCost()*(1-runfastAgentbusiness.getPaotuiCoefficient().doubleValue()/100-runfastShopper.getCoefficient().doubleValue()/100))+gr.getTip());
                        }

                        RunfastCreditlevel c=null;// // 信用等级管理
                        if(runfastShopper.getCreditLevelid()!=null){
                            c=creditLevelService.get(runfastShopper.getCreditLevelid());//查看信誉等级情况
                        }else{
                            List<RunfastCreditlevel> list=  creditLevelService.findAll();//  信用等级管理
                            if(list!=null&&list.size()>0){
                                c=list.get(0);
                            }
                        }

//                        if(c!=null){
//                            BigDecimal shopperMoney=BigDecimal.valueOf(0);
//                            if(c.getStarttimeday()!=null && c.getEndtimeday()!=null){
//                                Calendar calendar = Calendar.getInstance();
//                                int hour = calendar.get(Calendar.HOUR_OF_DAY);
//
//
//                                calendar.setTime(c.getStarttimeday());
//                                int startTime1 = calendar.get(Calendar.HOUR_OF_DAY);
//                                calendar.setTime(c.getEndtimeday());
//                                int endTime1 = calendar.get(Calendar.HOUR_OF_DAY);
//                                if(MyUtil.inTime(c.getStarttimeday(), c.getEndtimeday(), new Date())){//符合第一时段配送费
//                                    shopperMoney=c.getCommissionday();
//
//                                }else{
//                                    shopperMoney=c.getCommissionnight();
//                                }
//                                if(shopperMoney==null){
//                                    shopperMoney=BigDecimal.valueOf(0);
//                                }
//                                if(gr.getDistance()!=null){
//                                    if(gr.getDistance()!=null&&c.getDistan()!=null&&c.getPrice()!=null){//distan超出多少公里后额外加钱
//                                        Double distan=c.getDistan();
//                                        if(Double.parseDouble(String.valueOf(gr.getDistance()))>distan*1000){//当超出了范围后，计算超出的费用
//                                            double ss =  Double.parseDouble(String.valueOf(gr.getDistance())) - distan*1000;
//                                            ss = ss /1000;
//                                            if(ss%1!=0){
//                                                ss=  ss+1;
//                                            }
//                                            int sd = (int)ss;
//                                            BigDecimal priceshopper = c.getPrice().multiply(BigDecimal.valueOf(sd));  //额外每公里加多少钱
//                                            shopperMoney=shopperMoney.add(priceshopper);
//                                            if(c.getMaxprice()!=null){
//                                                if(shopperMoney.compareTo(c.getMaxprice())==1){
//                                                    shopperMoney = c.getMaxprice();
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                             //   gr.setShoppermoney(shopperMoney);
//                            }
//                        }


                        //订单状态操作记录
                   /*     RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();

                        goodsSellOutStatus.setCreatetime(new Date());
                        goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());
                        goodsSellOutStatus.setGoodssellrecordid(gr.getId());
                        goodsSellOutStatus.setOperationid(super.getLoginShopper(token).getId());
                        goodsSellOutStatus.setOperationname(runfastShopper.getName());
                        goodsSellOutStatus.setSort(3);*/
                        if(gr.getStatus()==Order.Status.PAID){
                            //    created=下单成功 canceled=取消订单  paid=付款成功 taken=排列 completed==订单完成
                          //  gr.setStype(1);
                            OrderStatusHistory orderStatusHistory=new OrderStatusHistory();
                            orderStatusHistory.setId(null);
                            orderStatusHistory.setStatus(Order.Status.TAKEN);
                            orderStatusHistory.setOrderId(gr.getId());
                            orderStatusHistory.setCreateTime(new Date());
                            orderStatusHistory.setUpdateTime(new Date());

                            orderStatusHistoryService.insertSelective(orderStatusHistory);//已接单

                        }else{

                        }



                        model.put("success",true);
                        model.put("msg","抢单成功");

                    /*    RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), 1);
                        if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(3))){
                            ////sort    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
                            goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
                        }*/
                        //RunfastGoodsSellRecord grtemp = goodsSellRecordService.get(id);// 外卖商品规格
                        Order grtemp=orderService.get(id);
                        if(grtemp != null &&  grtemp.getDriverId()==null)
                        {
//                            OrderStatusHistory orderStatusHistory=new OrderStatusHistory();

//                            orderStatusHistory.setCreateTime(new Date());
//                            orderStatusHistory.setUpdateTime(new Date());
//                            orderStatusHistory.setStatus(Order.Status.PAID);
//                            orderStatusHistory.setOrderId(gr.getId());
//                            orderStatusHistoryService.insertSelective(orderStatusHistory);//已接单
                            gr.setStatus(Order.Status.TAKEN);
                            gr.setTimeTaken(new Date());
                            gr.setPaid(true);
                            orderService.updateByPrimaryKeySelective(gr);
                         //   this.rabbitTemplate.convertAndSend("paotui", JSON.toJSONString(gr)); //保存在队列
                            amqpTemplate.convertAndSend("pt_shopper_exchange", "", JSON.toJSONString(gr));


                        }else{
                            model.put("success",false);
                            model.put("msg","订单已经被抢走了");

                        }
              //          amqpTemplate.convertAndSend("shopper__exchange", "", JSON.toJSONString(gr));
                        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                        model.put("success",true);
                        model.put("msg","抢单成功");
                    }else{
                        model.put("success",false);
                        model.put("msg","订单早已经被抢走");
                    }
                    runFastSettingts.removeTakeThatOrderId(id);//删除正在接单操作的订单id
                }else{
                    model.put("success",false);
                    model.put("msg","订单已经被其它骑手抢走");
                }
            }else{

                model.put("success",false);
                model.put("msg","未完成订单已达上限，请先完成手上订单!");
            }

        }

        return model;
    }
    /**
     * 送达
     */
    @RequestMapping(value="orderarrived",method=RequestMethod.POST)//验证
    public @ResponseBody ModelMap orderarrived(Integer id,String token){
        ModelMap model = new ModelMap();

        if(super.getLoginShopper(token)!=null&&id!=null){

          Order gr = orderService.findByShopperidAndCode(super.getLoginShopper(token).getId(),id);
            if(gr!=null&&gr.getStatus()!=null&&(gr.getStatus()==Order.Status.PICKED||gr.getStatus()==Order.Status.TAKEN)){
                //    created=下单成功 canceled=取消订单  paid=接单成功 taken=已付款 completed==订单完成 PICKED=待送达
                OrderStatusHistory orderStatusHistory=new OrderStatusHistory();
                orderStatusHistory.setId(null);
                orderStatusHistory.setStatus(Order.Status.COMPLETED);
                orderStatusHistory.setOrderId(gr.getId());
                orderStatusHistory.setCreateTime(new Date());
                orderStatusHistory.setUpdateTime(new Date());

                orderStatusHistoryService.insertSelective(orderStatusHistory);//已接单
                gr.setTaken(true);//设定为已收货

                gr.setStatus(Order.Status.COMPLETED);//订单完成
               // gr.setTimeCompleted(new Date());
                gr.setCompleted(true);
                gr.setTimeCompleted(new Date());//送达时间(添加送达时间)
                orderService.updateByPrimaryKeySelective(gr);///更新数据跑腿商品订单记录
           //     this.rabbitTemplate.convertAndSend("paotui", JSON.toJSONString(gr)); //保存在队列
                amqpTemplate.convertAndSend("pt_shopper_exchange", "", JSON.toJSONString(gr));
                //	goodsSellService.updateSalesnum(gr);//// 更新外卖商品
//              goodsSellRecordChildrenService.updateFindByPid(gr.getId(),4);//执行定单更新和返回INT
//
//                //订单状态操作记录
//                RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
//             /*   goodsSellOutStatus.setBusinessid(gr.getBusinessid());//设置商家ID
//                goodsSellOutStatus.setBusinessname(gr.getBusinessname());//设置商家名字*/
//                goodsSellOutStatus.setCreatetime(new Date());//设置订单时间
//                goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());//设置订单号
//                goodsSellOutStatus.setGoodssellrecordid(gr.getId());////商品订单ID
//                goodsSellOutStatus.setOperationid(super.getLoginShopper().getId());//设置骑手ID
//                goodsSellOutStatus.setOperationname(super.getLoginShopper().getName());//设置骑手姓名
//                goodsSellOutStatus.setSort(8);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
//                goodsSellOutStatus.setStatstr("订单完成");
//                goodsSellOutStatus.setType(2);///操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
//                RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
//                //  RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);
//                if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(8))||goodsSellOut.getSort()==null){
//                    goodsSellOutStatusService.save(goodsSellOutStatus);
//                }
//             /

//            System.out.println("id"+gr.getId()+"用户id"+gr.getCuserId()+"8888888888888888888888888888888888888");
                Integer id1=gr.getCuserId();
                RunfastCuser cuser=cuserService.get(id1);
                HashMap<String, String> params = new HashMap<>();
                params.put("orderCode", gr.getOrderNo());
                MsgPushUtils.pushToUser(10,params,"送达提醒","您的代购订单:"+gr.getOrderNo()+"已经送达",cuser.getAlias());

                model.put("msg","配送成功!");
                model.put("success", true);
            }else {
               if (gr.getStatus()==Order.Status.COMPLETED){
                   OrderStatusHistory orderStatusHistory=new OrderStatusHistory();

                   orderStatusHistory.setStatus(Order.Status.COMPLETED);
                   orderStatusHistory.setOrderId(gr.getId());
                   orderStatusHistory.setCreateTime(new Date());
                   orderStatusHistory.setUpdateTime(new Date());

                   orderStatusHistoryService.insertSelective(orderStatusHistory);//已接单

                   //这种情况下也是完成跑腿订单
                   gr.setTaken(true);//设定为已收货

                   gr.setStatus(Order.Status.COMPLETED);//订单完成
                   // gr.setTimeCompleted(new Date());
                   gr.setCompleted(true);
                   gr.setTimeCompleted(new Date());//送达时间(添加送达时间)
                   orderService.updateByPrimaryKeySelective(gr);///更新数据跑腿商品订单记录


                   model.put("msg","配送成功了");
                   model.put("success", true);
               }
            }

        }

        return model;
    }

}
